package com.imc.api.attence.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imc.api.attence.dao.LeaveMapper;
import com.imc.api.attence.dao.repository.LeaveDetailRepository;
import com.imc.api.attence.dao.repository.LeaveRepository;
import com.imc.api.attence.dao.LessonMapper;
import com.imc.api.attence.pojo.Leave;
import com.imc.api.attence.pojo.LeaveDetail;
import com.imc.api.order.pojo.Lesson;
import com.imc.core.utils.DateUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.leave.pojo.MakeMissLesson;
import com.imc.platform.base.leave.pojo.OptNote;
import com.imc.platform.base.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*
 * 类描述：请假服务类
 * 开发者：tanweiping
 * 创建日期：2018/10/28 20:58
 */
@Service
@Transactional
@Slf4j
public class LeaveService {

    @Autowired
    LeaveRepository leaveRepository;//请假仓库

    @Autowired
    LeaveDetailRepository leaveDetailRepository;//请假详情仓库

    @Autowired
    LessonMapper lessonMapper;//课程mapper

    @Autowired
    LeaveMapper leaveMapper;//请假mapper

    @Autowired
    MysqlUtil mysqlUtil;//数据库操作类

    /*
     * YT  2018/10/28 20:58
     * 方法描述：通过登陆名称为学生查询课程列表
     */
    public List <Lesson> getLessionListForStu(String forW, String loginName,String child) {
        val data = leaveMapper.getLessionListForStu(loginName,child, DateUtils.getCurrentDateDD());
        if (data.isEmpty()) return new ArrayList <>();

        User user = mysqlUtil.getUserByLoginName(loginName);
        data.forEach(s -> s.setLessonSchedule(forW.equals("forLeave") ? lessonMapper.querySchedule(child,String.valueOf(s.getId()),String.valueOf(user.getId())) : lessonMapper.queryScheduleForSign(String.valueOf(s.getId()))));

        return data;
    }

    /*
     * YT  2018/10/28 20:58
     * 方法描述：通过登陆名称为老师查询课程列表
     */
    public List <Lesson> getLessionListForTeach(String forW, String loginName) {
        val data = leaveMapper.getLessionListForTeach(loginName, DateUtils.getCurrentDate());

        if (data.isEmpty()) return new ArrayList <>();

        User user = mysqlUtil.getUserByLoginName(loginName);
        data.forEach(s -> s.setLessonSchedule(forW.equals("forLeave") ? lessonMapper.querySchedule("",String.valueOf(s.getId()), String.valueOf(user.getId())) : lessonMapper.queryScheduleForSign(String.valueOf(s.getId()))));

        return data;
    }

    /*
     * YT  2018/10/28 21:00
     * 方法描述：发起请假
     */
    public void postleave(Principal principal, Leave leave) throws Exception {
        User user = mysqlUtil.getUserByLoginName(principal.getName());
        leave.setUserId(String.valueOf(user.getId()));
        leave.setFlag(user.getDuty().equals("teacher") ? 1 : 0);
        Date d = new Date();
        leave.setCreateTime(d);
        leave.setUpdateTime(d);
        /*
        设置序列
         */
        if (leave.getLeaveDetails() == null || leave.getLeaveDetails().isEmpty()) throw new Exception("请假详情没有数据，发生异常");
        String teacherId = lessonMapper.getTeacherId(leave.getLeaveDetails().get(0).getScheduleId());
        leave.setAuditorId(teacherId);
        leaveRepository.save(leave);
        for (LeaveDetail detail : leave.getLeaveDetails()) {
            detail.setLeave(leave);
            detail.setCreateTime(d);
            detail.setUpdateTime(d);
            detail.setUserId(String.valueOf(user.getId()));
        }
        leaveDetailRepository.save(leave.getLeaveDetails());

    }

    /*
     * YT  2018/10/28 21:00
     * 方法描述：审核
     */
    public void audit(Principal principal, List <String> ids, String status) {
        if (ids == null || ids.isEmpty()) return;
        List <Leave> leaves = leaveRepository.findAllByIdIn(ids.stream().map(id -> Integer.parseInt(id)).collect(Collectors.toList()));
        User user = mysqlUtil.getUserByLoginName(principal.getName());
        Date d = new Date();
        leaves.forEach(
                l -> {
                    l.setStatus(Integer.parseInt(status));
                    l.setAuditorId(String.valueOf(user.getId()));
                    l.setUpdateTime(d);
                }
        );
        leaveRepository.save(leaves);
    }

    /*
     * twp  2018/10/28 21:01
     * 方法描述：获取请假列表
     */
    public List <Map <String, Object>> getLeaveList(Principal principal, String option, Pageable pageable) {
        User user = mysqlUtil.getUserByLoginName(principal.getName());

        val data = leaveMapper.getLeave(option, String.valueOf(user.getId()));

        if (data != null && !data.isEmpty()) {
            data.forEach(
                    d -> {
                        val detailList = leaveMapper.findByleaveId(String.valueOf(d.get("id")));
                        d.put("detailList", detailList);
                        d.put("checked", false);
                    }
            );
        }

        return data;

    }

    /*
     * twp  2018/10/28 21:01
     * 方法描述：获取请假列表
     */
    public List <Map <String, Object>> getLeaveListByPageable(Principal principal, String option, Pageable pageable) {
        User user = mysqlUtil.getUserByLoginName(principal.getName());

        val data = leaveMapper.getLeave(option, String.valueOf(user.getId()));

        if (data != null && !data.isEmpty()) {
            data.forEach(
                    d -> {
                        val detailList = leaveMapper.findByleaveId(String.valueOf(d.get("id")));
                        d.put("detailList", detailList);
                        d.put("checked", false);
                    }
            );
        }

        return data;

    }

    /*
     * YT  2018/10/28 21:01
     * 方法描述：通过ID删除请假信息
     */
    public void deleteLeavById(String id) {
        leaveMapper.cleanById(id);
        leaveRepository.delete(Integer.parseInt(id));
    }


    public void addMakeMissLesson(MakeMissLesson makeMissLesson){
        leaveMapper.addMakeMissLesson(makeMissLesson);
            OptNote optNote=OptNote.builder()
                    .optSubMod("makeMissLesson")
                    .optType("add")
                    .optUserId(makeMissLesson.getAuditorId())
                    .optResult(makeMissLesson.getId() != 0 ? "新增成功":"新增失败")
                    .build();
            leaveMapper.addOptNode(optNote);
    }

    public void updateMakeMissLesson(MakeMissLesson makeMissLesson){
        leaveMapper.updateMakeMissLesson(makeMissLesson);
        OptNote optNote=OptNote.builder()
                .optSubMod("makeMissLesson")
                .optType("update")
                .optUserId(makeMissLesson.getAuditorId())
                .optResult( "修改成功")
                .build();
        leaveMapper.addOptNode(optNote);
    }

    public Map<String,Object>showMakeMissLesson(int id){
        return leaveMapper.showMakeMissLesson(id);
    }

    public Map<String,Object> queryMakeMissLessonState(int id){
        return leaveMapper.queryMakeMissLessonState(id);
    }

    public List<MakeMissLesson>queryMakeList(String leaveDetId){
        return leaveMapper.queryMakeList(leaveDetId);
    }

    public Map<String,Object> queryLessonOrgName(int leaveDetId){
        return leaveMapper.queryLessonOrgName(leaveDetId);
    }

    public List<Map<String,Object>>queryMasterList(int orgId){
        return leaveMapper.queryMasterList(orgId);
    }

    public String queryProposer(int leaveDetId){
        return leaveMapper.queryProposer(leaveDetId);
    }

    public String queryMissLessonFormId(int id){
        return leaveMapper.queryMissLessonFormId(id);
    }

    public Map<String,Object>queryLessonOrgNameByMessId(int id){
        return leaveMapper.queryLessonOrgNameByMessId(id);
    }

    public PageInfo<Map<String,Object>>queryMissLessonList(Pageable pageable,String loginName){
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List <Map<String,Object>> missLessonList = leaveMapper.queryMissLessonList(loginName);
        PageInfo info = new PageInfo <>(missLessonList);
        return info;
    }
}
